import { AppConfig } from "@/core/configs/app.config";
import { RequestConfig } from "umi";
import { RequestOptionsInit } from "umi-request"

export const AuthorizationInterceptor: Pick<RequestConfig, 'requestInterceptor' | 'responseInterceptor'> = {
    requestInterceptor: (url: string, options: RequestOptionsInit) => {
        const cacheData = window.sessionStorage.getItem(AppConfig.AUTH_HEADER_NAME) as any;
        const jwtToken = cacheData ? JSON.parse(cacheData) : null
        if (jwtToken) {
            options.headers = { ...options.headers, Authorization: jwtToken }
        }
        return { url, options }
    },
    responseInterceptor: (response: Response) => {
        const jwtToken = response.headers.get(AppConfig.AUTH_HEADER_NAME);
        if (jwtToken) {
            window.sessionStorage.setItem(AppConfig.AUTH_HEADER_NAME, JSON.stringify(jwtToken))
            window.sessionStorage.setItem(AppConfig.AUTH_UPDATE_TIME, new Date().getTime().toString())
        }
        return response
    }
}